package com.qf.dblib.dao.impl;


import com.qf.dblib.DaoConstants;
import com.qf.dblib.dao.entity.UserInfo;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息控制类
 * 2020/2/24 21:18
 */
public class UserMgr {
    private static volatile UserMgr instance = null;
    private UserInfo mUserInfo;

    private UserMgr() {
    }

    public static UserMgr getInstance() {
        if (instance == null) {
            synchronized (UserMgr.class) {
                if (instance == null) {
                    instance = new UserMgr();
                }
            }
        }
        return instance;
    }

    /**
     * 保存用户信息
     */
    public boolean saveUser(UserInfo info) {
        if (info == null)
            return false;
        mUserInfo = info;
        mUserInfo.setStatus(DaoConstants.STATUS_ONLINE);
        return info.saveOrUpdate("uid = ?", info.getUid());
    }

    /**
     * 获取用户信息
     */
    public
    UserInfo getLoginUser() {
        if (mUserInfo == null) {
            List<UserInfo> userInfos = LitePal.where("status = ?", String.valueOf(DaoConstants.STATUS_ONLINE)).find(UserInfo.class);
            if (userInfos != null && userInfos.size() > 0) {
                mUserInfo = userInfos.get(0);
            }
        }
        return mUserInfo;
    }


    /**
     * 获取所有登录过得用户
     */
    public List<UserInfo> getAllUser() {
        List<UserInfo> all = LitePal.findAll(UserInfo.class);
        if (all == null)
            return new ArrayList<>();
        return all;
    }


    public void exitLogin() {
        if (mUserInfo != null) {
            List<UserInfo> userInfos = LitePal.where("status = ?", String.valueOf(DaoConstants.STATUS_ONLINE)).find(UserInfo.class);
            if (userInfos!= null && userInfos.size() > 0) {
                for (UserInfo userInfo : userInfos) {
                    if (userInfo.getStatus() == DaoConstants.STATUS_ONLINE) {
                        userInfo.setStatus(DaoConstants.STATUS_OFFLINE);
                        userInfo.saveOrUpdate("uid = ?", userInfo.getUid());
                    }
                }
            }
            mUserInfo = null;
        }
    }
}